package com.xiaoyudeguang.customizer;

import com.xiaoyudeguang.annotations.RequestMapping;
import com.xiaoyudeguang.annotations.RestController;
import io.swagger.v3.oas.models.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.customizers.GlobalOperationCustomizer;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import java.util.Arrays;
import java.util.List;

/**
 * @author 赵光
 */
@Component
public class CustomOperationCustomizer implements GlobalOperationCustomizer {

    public static final String EXTENSION_AUTHOR = "x-author";
    
    public static final String EXTENSION_ORDER = "x-order";

    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {
        RestController restController = handlerMethod.getBeanType().getAnnotation(RestController.class);
        if (restController != null) {
            operation.setTags(List.of(restController.tags()));
            if (StringUtils.isNotBlank(restController.author())) {
                operation.addExtension(EXTENSION_AUTHOR, restController.author());
            }
        }
        RequestMapping requestMapping = handlerMethod.getMethod().getAnnotation(RequestMapping.class);
        if (requestMapping != null) {
            if (StringUtils.isNotBlank(requestMapping.summary())) {
                operation.setSummary(requestMapping.summary());
                operation.setDescription(requestMapping.summary());
            }
            if (StringUtils.isNotBlank(requestMapping.description())) {
                operation.setDescription(requestMapping.description());
            }
            operation.addExtension(EXTENSION_ORDER, requestMapping.order());
            if (requestMapping.developers().length > 1 || !"".equals(requestMapping.developers()[0])) {
                operation.addExtension(EXTENSION_AUTHOR, Arrays.toString(requestMapping.developers()));
            }
        }
        return operation;
    }
}
